package fr.afcepf.ai89.esharing.data;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import fr.afcepf.ai89.esharing.entity.Aem;
import fr.afcepf.ai89.esharing.entity.Indisponibilite;
import fr.afcepf.ai89.esharing.entity.InvisibiliteAem;

@Stateless
public class DAOIndisponibilite implements IDAOIndisponibilite {
	
	@PersistenceContext(unitName = "ESharingPhase22")
	EntityManager em;

	@Override
	public Indisponibilite getIndispo(int idIndispo) {
		Query hql = em.createQuery("SELECT ind FROM Indisponibilite ind WHERE ind.idIndisponibiliteAem = :idInd");
		hql.setParameter("idInd", idIndispo);
		return (Indisponibilite) hql.getSingleResult();
	}

	@Override
	public List<Indisponibilite> getIndispos() {
		Query hql = em.createQuery("SELECT ind FROM Indisponibilite ind");
		return hql.getResultList();
	}

	@Override
	public List<Indisponibilite> getIndispos(Aem aem) {
		Query hql = em.createQuery("SELECT ind FROM Indisponibilite ind WHERE ind.aem = :aem");
		hql.setParameter("aem", aem);
		return hql.getResultList();
	}

	@Override
	public int addIndispo(Indisponibilite indispo) {
		em.persist(indispo);
		
		Query hql = em.createQuery("SELECT MAX(idIndisponibiliteAem) FROM Indisponibilite ind");
		int idIndipo = (Integer)hql.getSingleResult();
		
		return idIndipo;
	}

	@Override
	public int majIndispo(Indisponibilite indispo) {

		Indisponibilite newIndispo = em.find(Indisponibilite.class, indispo.getIdIndisponibiliteAem());

		newIndispo.setDateDebutIndisponibiliteAem(indispo.getDateDebutIndisponibiliteAem());
		newIndispo.setDateFinIndisponibiliteAem(indispo.getDateFinIndisponibiliteAem());
		
		em.merge(newIndispo);
		return newIndispo.getIdIndisponibiliteAem();
		
	}

	@Override
	public int retirerIndispo(Indisponibilite indispo) {
		
		indispo = em.find(Indisponibilite.class, indispo.getIdIndisponibiliteAem());
		indispo.setDateRetraitIndisponibiliteAem(new Date());
		
		return indispo.getIdIndisponibiliteAem();
		
	}

}
